package com.lzkjiot.service.gnss.transger.core.transfer.condition;

import com.lzkjiot.service.gnss.transger.core.DataInFrame;
import com.lzkjiot.service.gnss.transger.core.transfer.CacheData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 缓存前端接收机发送来的工况数据
 */
@Service
@Slf4j
public class ConditionCacheManager {

    private final int maxCacheSize = 10000;
    private final ConcurrentLinkedQueue<CacheData> cache = new ConcurrentLinkedQueue<>();
    private final ScheduledExecutorService cachePrintWorker = Executors.newScheduledThreadPool(1);


    @PostConstruct
    public void init() {
        log.info("## Start Condition Cache Print Worker ...");
        startCachePrintWorker();
    }

    public void add(CacheData value) {
        if (cache.size() >= maxCacheSize) {
            evictOldestEntry();
        }
        cache.add(value);
    }

    public CacheData get() {
        return cache.poll();
    }

    private void evictOldestEntry() {
        cache.poll();
    }

    private void startCachePrintWorker() {
        cachePrintWorker.scheduleAtFixedRate(() -> {
            log.info("####### GNSS condition cache size " + cache.size());
        }, 0, 60, TimeUnit.SECONDS);
    }
}
